# *_*coding:utf-8 *_*
import re
import time
from pathlib import Path

from dataclasses import dataclass

from base_m3u8 import DownLoad_M3U8


@dataclass
class Twitter(DownLoad_M3U8):
    def playlists_selector(self, playlists):
        # 如果传入的是播放列表，筛选格式清晰的优先
        real_playlists = []
        re_compile = re.compile(r".*/(\d*)x(\d*)")
        for playlist in playlists:
            match = re_compile.match(playlist.base_path)
            if not match:
                raise Exception(f"No Match! {playlist}")
            if len(match.groups()) != 2:
                raise Exception(f"Match Error {playlist}")
            # uri = urljoin(self.base_uri, playlist.base_path)
            real_playlists.append([
                playlist,
                int(match.group(1)),
                int(match.group(2))
            ])
        real_playlists.sort(key=lambda x: x[1] * x[2], reverse=True)
        return [real_playlists[0][0]]

    def download_all_ts(self):
        self.download_all_ts2()


def main():
    # 使用系统变量修改代理, 可以让m3u8解析也经过代理
    # os.environ["http_proxy"] = "http://127.0.0.1:10809"
    # os.environ["https_proxy"] = "https://127.0.0.1:10809"
    # print(os.environ)
    m3u8_url = 'https://video.twimg.com/ext_tw_video/1355555735401160712/pu/pl/qK8u6P8EzrpBicAm.m3u8?tag=10'
    m3u8_url = 'https://video.twimg.com/amplify_video/1357694165098795008/pl/hM4jzG__goh9WeF1.m3u8?tag=13'
    m3u8_url = 'https://video.twimg.com/ext_tw_video/1565666413787770880/pu/pl/PQd5cpQTI_k2FIu-.m3u8?variant_version=1&tag=12&container=fmp4'
    m3u8_url = 'https://video.twimg.com/ext_tw_video/1565916227612323840/pu/pl/cgzG0b8j1whn5Msc.m3u8?variant_version=1&tag=12&container=fmp4'
    m3u8_url = 'https://video.twimg.com/amplify_video/1596078772268150785/pl/GXz7A5t24XmGJm_4.m3u8?variant_version=1&tag=14&container=fmp4'

    file_name = ''
    out_path = Path(r"C:\download").joinpath(Path(__file__).stem)
    proxies = {
        'sock5': '127.0.0.1:10808',
        'http': '127.0.0.1:10809',
        'https': '127.0.0.1:10809'
    }
    # proxies = {}
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36',
    }
    download_proxies = proxies
    download_headers = {
        "Referer": "https://twitter.com/",
        "origin": "https://twitter.com",
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36',
    }

    start = time.time()
    M3U8 = Twitter(
        m3u8_url=m3u8_url,
        file_name=file_name,
        out_path=out_path,
        proxies=proxies,
        rm_ts=False,
        tmp_path="../",
        timeout=10,
        headers=headers,
        max_workers=1,
        download_headers=download_headers,
        download_proxies=download_proxies,
        check_all_ts=True,
        merge_ts=True,
    )
    # print(M3U8.config)
    M3U8.run()
    end = time.time()
    print('耗时:', end - start)


if __name__ == '__main__':
    main()
